package com.zhj.juc.demo10;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

/**
 * @PackageName:com.zhj.juc.demo10
 * @ClassName:Test1Forkjoin
 * @auter: 朱慧杰
 * @date:2020/7/24 0024 17:46
 **/
public class Test1Forkjoin extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    private Long temp = 10000L;

    public Test1Forkjoin(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    // 递归事件没有返回值 递归任务有返回值

    public static void main(String[] args) throws Exception {
        // ForkJoin 特点 ： 工作窃取 执行完会帮别的线程执行 双端队列
        // 求和计算
        long start = System.currentTimeMillis();
        System.out.println(getSum(10_0000_0000L));
        long end = System.currentTimeMillis();
        System.out.println(end-start);

        long start1 = System.currentTimeMillis();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new Test1Forkjoin(0L,10_0000_0000L);
        //forkJoinPool.execute(task);
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);
        System.out.println(submit.get());
        long end1 = System.currentTimeMillis();
        System.out.println(end1-start1);

        long start2 = System.currentTimeMillis();

        long sum = LongStream.rangeClosed(0L,10_0000_0000L).parallel().reduce(0,Long::sum);
        System.out.println(sum);
        long end2 = System.currentTimeMillis();
        System.out.println(end2-start2);
    }

    public static Long getSum(long n) {
        long sum = 0;
        for (long i = 0; i <= n; i++) {
            sum += i;
        }
        return sum;
    }

    // 计算方法
    @Override
    protected Long compute() {
        if ((end-start) < temp) {
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        } else {
            long middle = (start + end) / 2;  //中间值
            Test1Forkjoin forkjoin1 = new Test1Forkjoin(start,middle);
            forkjoin1.fork(); // 拆分任务 把任务压入线程对列
            Test1Forkjoin forkjoin2 = new Test1Forkjoin(middle+1,end);
            forkjoin2.fork(); // 拆分任务 把任务压入线程对列
            return forkjoin1.join()+forkjoin2.join();
        }

    }
}
